package com.petecat.interchan;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.petecat.interchan.base.project.entity.EsEwarningHardwareConfig;
import com.petecat.interchan.base.warning.config.entity.BsWarningConfig;
import com.petecat.interchan.base.warning.config.entity.EsEwarningHardWare;
import com.petecat.interchan.base.warning.config.entity.EsRemarkVO;
import com.petecat.interchan.base.warning.config.entity.EsWarningNoticeVO;
import com.petecat.interchan.base.warning.config.entity.WarningEmpl;
import com.petecat.interchan.base.warning.config.service.IWarningConfigService;
import com.petecat.interchan.es.EsDaoInter;
import com.petecat.interchan.protocol.sso.companyempl.vo.BsSmsQryVO;

@SpringBootTest
@RunWith(SpringRunner.class)
public class EsQueryWarningInfo {
	
	@Autowired
	private EsDaoInter esDao;
	
	@Autowired
	private IWarningConfigService warningConfigService;
	
	@Test
	public void findWarningEsByRuleId() {
		//warningConfigService.queryEsWarningNotice(userId);
		 TransportClient client = null;
		 String sourceAsString = null;
		 String ruleId = null;
		 BsWarningConfig warningConfig = null;
		 String configName = null;
		 String remark = null;
		 EsWarningNoticeVO warningNoticeVO = null;
		 EsRemarkVO esRemarkVO = null;
		 List<EsWarningNoticeVO> noticeList = new ArrayList<>();
		 //
		 List<EsRemarkVO> remarkVoList = new ArrayList<>();
		 //判断是否存在过
		 List<String> remarkList = new ArrayList<>();
		 List<String> configIdList = new ArrayList<>();
		 //存多个RuleId
		 List<String> ruleIdList = new ArrayList<>();
		//存多个备注
		 List<String> remarkAll = new ArrayList<>();
		//存多个备注次数
		 List<Integer> remarkCountAll = new ArrayList<>();
		 try {
			client = esDao.getClient();
			//预警状态
			TermQueryBuilder ewarningStatus = QueryBuilders.termQuery("ewarningStatus", "1");
			//未读条件
			TermQueryBuilder readStatus = QueryBuilders.termQuery("readStatus", "0");
			BoolQueryBuilder must = QueryBuilders.boolQuery().must(ewarningStatus).must(readStatus);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware").setSize(100)
														  	 .setQuery(must)
															 .execute().actionGet();
			SearchHits hits = actionGet.getHits();
			int y = 0;
			if(hits.getHits().length > 0) {
				for (SearchHit hit : hits.getHits()) {
					sourceAsString = hit.getSourceAsString();
					JSONObject warningObject = JSONObject.parseObject(sourceAsString);
					ruleId = warningObject.getString("id");
					warningConfig = warningConfigService.getEwarningConfigIdByRuleId(ruleId);
					if(configIdList.contains(warningConfig.getId())) {
						//设置配置数量+1
						warningNoticeVO.setConfigCount(warningNoticeVO.getConfigCount()+1);
						remark = warningObject.getString("remark");
						if(remarkList.contains(remark)){
							int a = remarkCountAll.get(y).intValue();
							remarkCountAll.set(y, a+1);
						}else {
							y++;
							remarkCountAll.add(1);
							remarkAll.add(remark);
							//添加RuleId
							ruleIdList.add(ruleId);
						}
					}else {
						warningNoticeVO = new EsWarningNoticeVO();
						configIdList.add(warningConfig.getId());
						configName = warningConfig.getName();
						warningNoticeVO.setConfigCount(1);
						warningNoticeVO.setConfigName(configName);
						esRemarkVO = new EsRemarkVO();
						remark = warningObject.getString("remark");
						remarkAll.add(remark);
						remarkCountAll.add(1);
						//设置备注
						esRemarkVO.setRemarkList(remarkAll);
						//设置次数
						esRemarkVO.setRemarkCountList(remarkCountAll);
						//添加RuleId
						ruleIdList.add(ruleId);
						esRemarkVO.setRuleIdList(ruleIdList);
						//存到List判断是否存在了
						remarkList.add(remark);
						remarkVoList.add(esRemarkVO);
						warningNoticeVO.setRemarkVOList(remarkVoList);
						
						noticeList.add(warningNoticeVO);
					}
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null ) {
				esDao.resume(client);
			}
		}
		if(noticeList.size() > 0) {
			for (EsWarningNoticeVO vo : noticeList) {
				System.out.println(vo.getConfigName()+"|"+vo.getRemarkVOList().size());
			}
		}
	}
	
	private String ruleId;
	
	private String esId;
	
	@Before
	public void preSetData() {
		ruleId = "958908653056851968";
		esId = "AWFzNeMXooi_dBsdJxyw";
	}	
	
	/**
	 * 通过规则ID查询对应的预警信息
	 */
	@Test
	public void getWarningByRuleId() {
		TransportClient client = null;
		String sourceAsString = "";
		List<EsEwarningHardWare> wareList = new ArrayList<>();
		EsEwarningHardWare ewarningHardWare = new EsEwarningHardWare();
		JSONObject parseObject = null;
		List<WarningEmpl> emplList = null;
		WarningEmpl empl = null;
		try {
			client = esDao.getClient();
			//设置规则ID为条件
			TermQueryBuilder ruleIdQuery = QueryBuilders.termQuery("id", ruleId);
			//预警状态
			TermQueryBuilder ewarningStatus = QueryBuilders.termQuery("ewarningStatus", "1");
			//未读条件
			TermQueryBuilder readStatus = QueryBuilders.termQuery("readStatus", "0");
			BoolQueryBuilder must = QueryBuilders.boolQuery().must(ruleIdQuery).must(ewarningStatus).must(readStatus);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware").setSize(100)
														  	 .setQuery(must)
															 .execute().actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				for (SearchHit hit : hits.getHits()) {
					emplList = new ArrayList<>();
					sourceAsString = hit.getSourceAsString();
					parseObject = JSONObject.parseObject(sourceAsString);
					ewarningHardWare.setId(hit.getId());
					ewarningHardWare.setReadStatus(parseObject.getString("readStatus"));
					ewarningHardWare.setRemark(parseObject.getString("remark"));
					ewarningHardWare.setStopTime(parseObject.getString("stopTime"));
					ewarningHardWare.setRuleId(parseObject.getString("id"));
					ewarningHardWare.setEwarningStatus(parseObject.getString("ewarningStatus"));
					ewarningHardWare.setTitle(parseObject.getString("title"));
					ewarningHardWare.setSendTime(parseObject.getString("sendTime"));
					//获取用户List信息
					JSONArray jsonArray = parseObject.getJSONArray("user");
					Iterator<Object> iterator = jsonArray.iterator();
					while (iterator.hasNext()) {
						JSONObject next =  (JSONObject)iterator.next();
						empl = new WarningEmpl();
						empl.setEmail(next.getString("email"));
						empl.setIsEmail(next.getString("isEmail"));
						empl.setIsSms(next.getString("isSms"));
						empl.setRuleId(next.getString("ruleId"));
						empl.setSms(next.getString("sms"));
						empl.setUserId(next.getString("userId"));
						empl.setUserName(next.getString("userName"));
						emplList.add(empl);
					}
					ewarningHardWare.setEmplList(emplList);
					wareList.add(ewarningHardWare);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null) {
				esDao.resume(client);
			}
		}
	}
	
	/**
	 * 根据ID修改指定的 是否已读状态
	 */
	@Test
	public void updateEsWarningReadStatusById() {
		String id = "AWFj5f4Mooi_dBsdJwLG";
		TransportClient client = null;
		
			try {
				client = esDao.getClient();
				UpdateRequest uRequest = new UpdateRequest();
				uRequest.index("monitor-ewarning-hardware");
				uRequest.id(id);
				uRequest.type("monitor-ewarning-hardware");
				uRequest.doc(XContentFactory.jsonBuilder()
											.startObject()
											.field("readStatus", "1")
											.endObject());
				client.update(uRequest);
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				if(client != null) {
				esDao.resume(client);
				}
			}
		
	}
	

	/**
	 * 通过EsID查询对应的预警人员
	 */
	@Test
	public void getWarningEmplByEsId() {
		String sourceAsString = "";
		EsEwarningHardWare ewarningHardWare = new EsEwarningHardWare();
		JSONObject parseObject = null;
		List<WarningEmpl> emplList = null;
		WarningEmpl empl = null;
		TransportClient client = null;
		client = esDao.getClient();
		EsEwarningHardwareConfig config = null;
		try {
			TermQueryBuilder termQuery = QueryBuilders.termQuery("_id", esId);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware")
									.setQuery(termQuery)
									.execute()
									.actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				for (SearchHit hit : hits.getHits()) {
					emplList = new ArrayList<>();
					sourceAsString = hit.getSourceAsString();
					parseObject = JSONObject.parseObject(sourceAsString);
					//获取用户List信息
					JSONArray jsonArray = parseObject.getJSONArray("user");
					config = parseObject.getObject("config", EsEwarningHardwareConfig.class);
					Iterator<Object> iterator = jsonArray.iterator();
					while (iterator.hasNext()) {
						JSONObject next =  (JSONObject)iterator.next();
						empl = new WarningEmpl();
						empl.setEmail(next.getString("email"));
						empl.setIsEmail(next.getString("isEmail"));
						empl.setIsSms(next.getString("isSms"));
						empl.setRuleId(next.getString("ruleId"));
						empl.setSms(next.getString("sms"));
						empl.setUserId(next.getString("userId"));
						empl.setUserName(next.getString("userName"));
						emplList.add(empl);
					}
					ewarningHardWare.setConfig(config);
					ewarningHardWare.setEmplList(emplList);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null) {
				esDao.resume(client);
			}
		}
		
		
	}
	
	/**
	 * 通过EsID查询对应的预警人员
	 */
	@Test
	public void getWarningRuleInfoByEsId() {
		String sourceAsString = "";
		JSONObject parseObject = null;
		TransportClient client = null;
		EsEwarningHardwareConfig config = null;
		try {
			client = esDao.getClient();
			TermQueryBuilder termQuery = QueryBuilders.termQuery("_id", esId);
			SearchResponse actionGet = client.prepareSearch("monitor-ewarning-hardware")
									.setQuery(termQuery)
									.execute()
									.actionGet();
			SearchHits hits = actionGet.getHits();
			if(hits.getHits().length > 0) {
				for (SearchHit hit : hits.getHits()) {
					sourceAsString = hit.getSourceAsString();
					parseObject = JSONObject.parseObject(sourceAsString);
					config = parseObject.getObject("config", EsEwarningHardwareConfig.class);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(client != null) {
				esDao.resume(client);
			}
		}
	}
	
}
